import axios from 'axios'
import { MessageBox, Message, Loading } from 'element-ui'
import store from '@/store'
import { getToken } from '@/framework/utils/auth'
import { tansParams, blobValidate } from '@/framework/utils/index'
import errorCode from '@/framework/utils/errorCode'
import router from '@/router'
import { saveAs } from 'file-saver'
import qs from 'qs'

let downloadLoadingInstance
// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  baseURL: handleDealBaseURL(),
  // baseURL: 'http://18.10.255.5:8081',
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000 // request timeout
})

function handleDealBaseURL() {
  // 处理baseurl
  if (process.env.VUE_APP_BUILD_APP === 'true') {
    // 打包成app
    return process.env.VUE_APP_TARGET
  } else {
    return process.env.VUE_APP_BASE_API
  }
}

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent
    store.dispatch('settings/changeSetting', {
      key: 'dataText',
      value: ' '
    })
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = getToken()
      if (config.responseType) {
        config.responseType = 'blob'
      }
    }
    if (config.method === 'get') {
      config.paramsSerializer = function (params) {
        return qs.stringify(params, { arrayFormat: 'repeat' }) // vue中axios解决get请求传输数据是数组格式问题
      }
    }
    return config
  },
  (error) => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const res = response.data
    if (response.data.type === 'application/octet-stream') {
      return response
    }
    if (response.data instanceof Blob) {
      return response
    }
    // if the custom code is not 00000, it is judged as an error.
    if (res.code !== '00000') {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      if (process.env.VUE_APP_AUTHENTICATION_FLAG && res.code === 'B10000') {
        router.push({
          path: '/authentication'
        })
      }
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 'B0301' || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.alert('登录已过期，请重新登录。', '提示', {
          confirmButtonText: '确定',
          type: 'error'
        })
          .then(() => {
            store.dispatch('user/resetToken').then(() => {
              location.reload()
            })
          })
          .catch(() => {})
      }
      // return res
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      if (
        res.data?.rows?.length === 0 ||
        res.data?.length === 0 ||
        res.data?.rows === null
      ) {
        store.dispatch('settings/changeSetting', {
          key: 'dataText',
          value: '暂无数据'
        })
      }
      return res
    }
  },
  (error) => {
    const { response } = error
    const { code } = response.data
    if (code === 'B03500') {
      return Promise.reject(response.data)
    }
    if (
      process.env.VUE_APP_AUTHENTICATION_FLAG === 'true' &&
      code === 'B10000'
    ) {
      router.push({
        path: '/authentication'
      })
      return
    } else if (code === 'B0301' || code === 50012 || code === 50014) {
      // store.dispatch('user/resetToken').then(() => {
      //   location.reload()
      // })
      MessageBox.alert('登录已过期，请重新登录。', '提示', {
        confirmButtonText: '确定',
        type: 'error'
      })
        .then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
        .catch(() => {})
    }
    if (response.data.code === 'B0301') return
    Message({
      message: response.data.message,
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject(response.data)
  }
)

// 通用下载方法
export function download(url, params, filename) {
  downloadLoadingInstance = Loading.service({
    text: '正在下载数据，请稍候',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  return service
    .post(url, params, {
      transformRequest: [
        (params) => {
          return tansParams(params)
        }
      ],
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      responseType: 'blob'
    })
    .then(async (data) => {
      const isLogin = await blobValidate(data)
      if (isLogin) {
        const blob = new Blob([data])
        saveAs(blob, filename)
      } else {
        const resText = await data.text()
        const rspObj = JSON.parse(resText)
        const errMsg =
          errorCode[rspObj.code] || rspObj.msg || errorCode['default']
        Message.error(errMsg)
      }
      downloadLoadingInstance.close()
    })
    .catch((r) => {
      Message.error('下载文件出现错误，请联系管理员！')
      downloadLoadingInstance.close()
    })
}

const mock = process.env.VUE_APP_MOCK === 'true' ? '/mock/15' : ''

const cloud =
  process.env.VUE_APP_CLOUD_ON === 'true'
    ? {
      dqbasic: '/project',
      notice: '/notice',
      tenant: '/tenant',
      auth: '/auth',
      file: '/file',
      usercenter: '/usercenter',
      manage: '/manage',
      datasync: '/datasync',
      permission: `${mock}/permission`,
      process: `${mock}/workflow`,
      business: '/business',
      videofusion: '/videofusion',
      unifiedRelease: '/release',
      devcenter: '/devcenter',
      interfacePlatform: '/interfacePlatform',
      unifiedPayment: '/unifiedPayment',
      // mall: 'http://18.0.136.158:21145',
      mall: 'https://y47931706h.vicp.fun',
      onlineClass: '/onlineClass',
      investment: '/investment',
      assess: '/assessmentRecords',
    }
    : {
      dqbasic: '',
      notice: '',
      auth: '',
      tenant: '',
      file: '',
      usercenter: '',
      manage: '',
      datasync: '',
      permission: '',
      process: '',
      business: '',
      unifiedreport: '',
      videofusion: '',
      unifiedRelease: '',
      devcenter: '',
      interfacePlatform: '',
      unifiedPayment: '',
      mall: '',
      onlineStudy: '',
      investment: '',
      assess: ''
    }
export { cloud }
export default service
